import Koa from 'koa'
import Router from 'koa-router'
import bodyparser from 'koa-bodyparser'
import { Datatypes, Sequelize, Op} from 'sequelize'

let koa=new Koa();
let router=new Router();

let sequelize=new Sequelize('test','sa','123456',{
    host:'localhost',
    dialect:'mssql'
});

let Blogs=sequelize.define('Blogs',{
    title:{type:Datatypes.STRING},
    content:{type:Datatypes.STRING},
    flog:{type:Datatypes.STRING}
})

await Blogs.sync();

router.post('/blogs',async(ctx)=>{
    let obj=ctx.request.body;
    let list=await Blogs.create(obj);
    ctx.body={
        code:1000,
        data:list,
        msg:'新增成功'
    }
});

router.get('/blogs/:id?',async(ctx)=>{
    let id=ctx.params.id ||0;
    if(id>0){
        let list=await Blogs.findByPk(id);
        ctx.body={
            code:1000,
            data:list,
            msg:'查找指定id成功'
        }
    }else{
        let list=await Blogs.findAll();
        ctx.body={
            code:1000,
            data:list,
            msg:'查找所有数据成功'
        }
    }
});

router.delete('/blogs/:id',async(ctx)=>{
    let id=ctx.params.id ||0;
    let obj=await Blogs.findByPk(id);
    if(obj){
        await Blogs.destroy({
            where:{
                id:id
            }
        })
    }
    ctx.body={
        code:1000,
        data:[],
        msg:'删除成功'
    }
});

router.put('/blogs/:id',async(ctx)=>{
    let id=ctx.params.id || 0;
    let obj=ctx.request.body;
    let list=await Blogs.findByPk(id);
    if(list>0){
        let data=await Blogs.update(obj,{
            where:{
                id:id
            }
        })
        
    }
})




koa.use(router.routes);
koa.use(bodyparser);
koa.listen(port,()=>{
    console.log(`服务器运行在http://localhost:${port}上`);
})